package com.jnxx.task.controller;


import com.jnxx.basic.util.GetStaffRequestUtil;
import com.jnxx.task.WxUtils.TokenUtils;
import com.jnxx.task.WxUtils.WeChatUtils;
import com.jnxx.task.WxVo.UserDetailResponse;
import com.jnxx.task.WxVo.UserDetailResponseMore;
import com.jnxx.task.WxVo.UserInfoResponse;
import com.jnxx.task.domain.OkrStaff;
import com.jnxx.task.service.IOkrStaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class WechatController {

    @Autowired
    private IOkrStaffService staffService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String corpId = "ww4009210d5c2665df";
    private final String secret = "MdazgK3RX3HcC_bmwORn9lnfPcoK6wz85a9hLpZjYt0";
    private final String redirectUri;
    @Autowired
    private WeChatUtils weChatUtils;
    {
        try {
            // 在HTTP GET请求中传输中文参数时不会丢失 qy.llczy.com
            redirectUri = URLEncoder.encode("http://qy.llczy.com", "UTF-8");
//            redirectUri = URLEncoder.encode("http://47.110.49.47:9080/api/app", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    // 企业可信ip：183.220.61.219;47.109.106.134;47.110.49.47
    // https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE&agentid=AGENTID#wechat_redirect
    // 微信登录页面URL模板，其中的%s将在运行时替换为实际的corpId和redirectUri
    private final String wechatLoginUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000033#wechat_redirect";
//    private final String wechatLoginUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000033#wechat_redirect";
    private final Map<String, Long> lastRequestTimes = new HashMap<>();
    private static final long THROTTLE_THRESHOLD = 1000;

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate2;

    /**
     * 自建应用配置的主页
     * @return
     */
    @GetMapping("/api/home")
    public ResponseEntity<String> home() {
        log.info("进入应用");
        System.out.println("进入应用");
        // ResponseEntity表示整个 HTTP 响应，包括状态码，标头和正文
        return ResponseEntity.status(302).header("Location", String.format(wechatLoginUrl, corpId, redirectUri)).build();
    }
  /**
     * 登录并返回用户信息至应用主页
     *  构建网页授权 https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID
     *              &redirect_uri=REDIRECT_URI
     *              &response_type=code
     *              &scope=snsapi_base
     *              &state=STATE&agentid=AGENTID#wechat_redirect
     * @return
     */
  @GetMapping("/api/app")
  public OkrStaff app(@RequestParam String code, HttpSession session, HttpServletResponse response) {
      log.info("code为：{}", code);
      //如果系统上线，提前预热数据，根据code,获取到用户的id,判断数据库是否有该用户，无，存入，有
      // 获取AccessToken
      String accessToken = tokenUtils.getAccessToken();

      log.info("accessToken为：{}", accessToken);
      // 发送一个GET请求，获取用户信息
      String userInfoUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token=%s&code=%s", accessToken, code);
      ResponseEntity<UserInfoResponse> userInfoResponse = restTemplate.getForEntity(userInfoUrl, UserInfoResponse.class);
      log.info("返回用户信息为：{}", userInfoResponse);

      // getUser_ticket 获取用户信息或敏感信息
//      String userid = userInfoResponse.getBody().getUserid();
      String userid = Objects.requireNonNull(userInfoResponse.getBody()).getUserid();
      if (userid == null){
          log.error("无效的userid");
          return null;
      }
      // 拉所有人
//      weChatUtils.getDepartmentListAndUserDetails(accessToken);
      // 先查有无此人
      OkrStaff staffTmp = staffService.findByUserId(userid);
      // 获取用户详细信息，头像
      HttpEntity<String> request = new HttpEntity<>(String.format("{\"user_ticket\":\"%s\"}", userInfoResponse.getBody().getUser_ticket()));
      String userDetailUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=%s", accessToken);
      ResponseEntity<UserDetailResponse> userDetailResponse = restTemplate.postForEntity(userDetailUrl, request, UserDetailResponse.class);
      // 获取到头像
      String avatar = userDetailResponse.getBody().getAvatar();
      String phone = userDetailResponse.getBody().getMobile();
      OkrStaff staff = new OkrStaff();
      // 如果无
      if (staffTmp == null){

          // 获取用户详细信息，姓名
          String userDetailMoreUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=%s&userid=%s", accessToken ,userid);
          ResponseEntity<UserDetailResponseMore> userDetailResponseMore = restTemplate.postForEntity(userDetailMoreUrl, request, UserDetailResponseMore.class);
          log.info("用户信息: {}" , userDetailResponseMore);
          String name = userDetailResponseMore.getBody().getName();
          staff.setName(name);
          staff.setAvatar(avatar);
          staff.setPhone(phone);
          staff.setUserId(userid);
          staff.setScore("0");
          staffService.add(staff);
      } else {
          // 如果有
          // 判断头像是否一致
//          if (!staffTmp.getAvatar().equals(avatar)){
              staff.setId(staffTmp.getId());
              staff.setAvatar(avatar);
              staff.setDepartmentId(staffTmp.getDepartmentId());
              staff.setName(staffTmp.getName());
              staff.setUserId(userid);
              staff.setScore(staffTmp.getScore());
              staff.setPhone(phone);
              staffService.update(staff);
              return staff;
//          }
//          return staffTmp;
      }
      log.info("姓名：{}", staff.getName());
      log.info("userId为：{}", userid);
      return staff;
  }

    @GetMapping("/api/getUserInfo2/{userId}")
    public OkrStaff getUserInfo2(@PathVariable("userId") String userId) {
        log.info("userId为：{}", userId);
        String key="user:" + userId;
        OkrStaff staff = staffService.findByUserId(userId);
        log.error("登录成功，姓名：{}",staff.getName());
        String loginKey = "login:" + userId;
        redisTemplate2.opsForValue().set("loginKey", staff, 60, TimeUnit.MINUTES);

        return staff;
    }

    // 添加任务之后，向企业微信成员发送消息
    @PostMapping("/api/sendMessage")
    public String sendMessage(@RequestBody Map<String, String> touser){

        try {
            String accessToken = stringRedisTemplate.opsForValue().get("accessToken");
            if (accessToken == null){
                accessToken = tokenUtils.getAccessToken();
            }
            String url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken;
//            String descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的任务下发，请点击查看</div><div class=\"highlight\"></div>";
            String descript = touser.get("descript");
            String nowTime = GetStaffRequestUtil.getNowTime();
            // 设置时间
            String descriptin = String.format(descript, nowTime);

            Map<String, String> textcard = new HashMap<>();
            textcard.put("title","任务通知");
            textcard.put("description", descriptin);
            textcard.put("url","qy.llczy.com");
//            textcard.put("url","qy.llczy.com/#/pages/showList/showList?userId=SunHeng");
            textcard.put("btntxt","更多");

            Map<String, Object> sendMessageMap = new HashMap<>();
            sendMessageMap.put("touser", touser.get("touser"));
            sendMessageMap.put("msgtype", "textcard");
            sendMessageMap.put("agentid", "1000033");
            sendMessageMap.put("textcard", textcard);
            sendMessageMap.put("safe", "0");
            sendMessageMap.put("enable_id_trans", "0");
            sendMessageMap.put("enable_duplicate_check", "0");
            //  183.220.61.219;47.109.106.134;47.110.49.47  183.220.61.219
            return restTemplate.postForObject(url, sendMessageMap, String.class);
//            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败";
        }

    }
}
